package com.example.controller;

import com.example.RestExceptionResolver;
import com.example.ReturnFormat;
import com.example.pojo.Account;
import com.example.services.AccountServiceImpl;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.List;

/**
 * Created by wushuai on 17/8/31.
 */
@Controller
@RequestMapping("/account")
public class AccountController extends RestExceptionResolver {

    private static final Logger logger = LoggerFactory.getLogger(HomeController.class);

    @Autowired
    private AccountServiceImpl accountService;

    @ResponseBody
    @RequestMapping("/login")
    public String findUser (@RequestParam("username") String un,
                            @RequestParam("password") String pw) {
        logger.info("findUserById:"+un);

        Account account = accountService.findUser(un, pw);
        if (account != null) { return ReturnFormat.retParam(200, JSONObject.fromObject(account).toString()); }
        return ReturnFormat.retParam(1012, null);
    }

    @ResponseBody
    @RequestMapping("/addAccount")
    public String addAccount (@RequestParam("username") String username,
                            @RequestParam("password") String password) {
        if (accountService.addAccount(username, password)) {
            return ReturnFormat.retParam(200, null);
        }http://git.sxb.lol/web/android.git
        return ReturnFormat.retParam(400, null);
    }

    @ResponseBody
    @RequestMapping("/findAll")
    public List<Account> findAll () {
        return accountService.findAll();
    }
}
